#!/bin/bash
#
#  Copyright (c) 2025, The OpenThread Authors.
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#  3. Neither the name of the copyright holder nor the
#     names of its contributors may be used to endorse or promote products
#     derived from this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#  POSSIBILITY OF SUCH DAMAGE.
#

CMAKE_TARGET="$2"

arm-none-eabi-objdump -S -C -l "${OUT_FOLDER}/bin/${CMAKE_TARGET}" > "${OUT_FOLDER}/bin/${CMAKE_TARGET}.asm"

if [ "$1" = "bank1" ]; then
    BIN_FILE="${OUT_FOLDER}/bin/${CMAKE_TARGET}_bank1.bin"
    MP_FILE="${OUT_FOLDER}/bin/${CMAKE_TARGET}_bank1_MP.bin"
    TRACE_FILE="${OUT_FOLDER}/bin/${CMAKE_TARGET}_bank1.trace"
else
    BIN_FILE="${OUT_FOLDER}/bin/${CMAKE_TARGET}_bank0.bin"
    MP_FILE="${OUT_FOLDER}/bin/${CMAKE_TARGET}_bank0_MP.bin"
    TRACE_FILE="${OUT_FOLDER}/bin/${CMAKE_TARGET}_bank0.trace"
fi

arm-none-eabi-objcopy -O binary -S "${OUT_FOLDER}/bin/${CMAKE_TARGET}" "${BIN_FILE}" --remove-section=App.trace
arm-none-eabi-objcopy -O binary -S "${OUT_FOLDER}/bin/${CMAKE_TARGET}" "${TRACE_FILE}" --only-section=App.trace


chmod +x "${REALTEK_SDK_PATH}/tools/prepend_header/prepend_header"
chmod +x "${REALTEK_SDK_PATH}/tools/md5/MD5"

"${REALTEK_SDK_PATH}/tools/prepend_header/prepend_header" -t app_code -b 15 -p "$BIN_FILE" -m 1 \
    -i "${OT_SRCDIR}/src/bee4/common/mp.ini" \
    -r "${REALTEK_SDK_PATH}/tools/keys/rtk_ecdsa.pem" \
    -a "${REALTEK_SDK_PATH}/tools/keys/key.json"

"${REALTEK_SDK_PATH}/tools/md5/MD5" "${MP_FILE}"
